# 合并区间

class Solution:

    def merge(self, intervals: list[list[int]]):
        # 按照第一个元素从小到大进行排序
        intervals.sort(key = lambda x: x[0])

        ans = []

        n , i = len(intervals), 0

        while i < n:

            left, right = intervals[i]

            while i < n - 1 and right >= intervals[i + 1][0]:

                right = max(right, intervals[i + 1][1])
                i += 1

            ans.append([left, right])

            i += 1

        
        return ans
    

if __name__ == "__main__":

    intervals = [[1,3],[2,6],[8,10],[15,18]]
    sol = Solution()
    ans = sol.merge(intervals)

    print(ans)


